package com.edu.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.demo.entity.*;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.service.IContractService;
import com.edu.demo.service.IProjectService;
import com.edu.demo.service.IReportService;
import com.edu.demo.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

/**报告表 前端控制器
 * </p>
 *
 * @author jixuewei
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/report")
public class ReportController {


    @Autowired
    private IReportService reportService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IContractService contractService;


    /**
     * 学生添加一个周报告
     * @param report
     * @return
     */
    @PostMapping("/add")
    @PreAuthorize("@ps.hasPerm('stu:report:add')")
    public AjaxResult addReport(@RequestBody Report report){
        report.setReportTime(new Date());
        report.setStuName(SecurityUtils.getStudent().getName());
        report.setStuId(SecurityUtils.getStudent().getId());

        Report thisWeek = reportService.selectThisWeek(new Date(), report.getProjectId());
        if(!Objects.isNull(thisWeek)){
            return AjaxResult.error("本周报告已经提交");
        }

        boolean save = reportService.save(report);
        if(save)return AjaxResult.success();
        return AjaxResult.error("保存失败");
    }

    /**
     * 教师、学生查看某个项目的周报告
     * @param projectId
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("@ps.hasPerm('user:report:list')")
    public AjaxResult list(@RequestParam Integer projectId,@RequestParam Integer index ,@RequestParam Integer size){
        Project project = projectService.getById(projectId);
        if(project==null){
            return AjaxResult.error("没有该项目");
        }
        Student student = SecurityUtils.getStudent(); //如果是学生查询自己的报告
        if(!Objects.isNull(student)){
            AtomicBoolean flag = new AtomicBoolean(false);
            List<Contract> contracts = contractService.list(new QueryWrapper<Contract>().eq("project_id", projectId));
            contracts.forEach(contract -> {if(contract.getStuId() == student.getId()) flag.set(true);});
            if(!flag.get()){
                return AjaxResult.error("只能查看自己参加的项目报告");
            }
        }

        Teacher teacher = SecurityUtils.getTeacher();
        if(!Objects.isNull(teacher)){
           if(project.gettId()!=teacher.getId()){
               return AjaxResult.error("只能查看自己的项目报告");
           }
        }


        QueryWrapper<Report> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id",projectId);
        queryWrapper.orderByDesc("report_time");
        Page<Report> page = new Page<>(index, size);
        page.setCurrent(index);
        page.setSize(size);
        Page<Report> reportPage = reportService.page(page, queryWrapper);
        List<Report> records = reportPage.getRecords();
//        List<Report> list = reportService.list(queryWrapper);
        AjaxResult success = AjaxResult.success(records);
        success.put("total",reportPage.getTotal());
        return success;
    }

    /**
     * 教师将报告更新为已读
     * @param report
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("@ps.hasPerm('tea:report:check')")
    public AjaxResult updateReport(@RequestBody Report report){

        report.setStatus((byte) 1);
        boolean b = reportService.updateById(report);
        if(b) return AjaxResult.success();
        return AjaxResult.error("修改失败");
    }
}
